package com.lzh.dlykserver.service.impl;

import com.lzh.dlykserver.entity.TTran;
import com.lzh.dlykserver.mapper.TTranMapper;
import com.lzh.dlykserver.query.TranQuery;
import com.lzh.dlykserver.service.TranService;
import com.lzh.dlykserver.util.JWTUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

@Service
@RequiredArgsConstructor
public class TranServiceImpl implements TranService {

    private final TTranMapper tTranMapper;

    @Override
    public Boolean insertTran(TranQuery tranQuery) {
        TTran tTran = new TTran();
        BeanUtils.copyProperties(tranQuery, tTran);


        // 登录人的id
        Integer loginUserId = JWTUtils.parseUserFromJWT(tranQuery.getToken()).getId();
        tTran.setCreateBy(loginUserId);
        tTran.setCreateTime(new Date());

        //  获取当前时间戳（精确到毫秒）
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());

        //  生成3位随机数
        int random = new Random().nextInt(900) + 100;  // 100 ~ 999 之间的随机数

        //  拼接成交易流水号
        tTran.setTranNo(timeStamp + random);

        int i = tTranMapper.insertSelective(tTran);
        return i >= 1;
    }

    @Override
    public int countByCustomerId(Integer customerId) {
        return tTranMapper.countByCustomerId(customerId);
    }
}
